package com.hcinfos.gsoo.ui;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.PoiEnity;
import com.hcinfos.gsoo.adapter.PoiResultAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.enity.MapInfo;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;

public class AddressActivity extends Activity implements OnClickListener {

	private ImageView marker_iv;
	private TextView address_tv;
	private MapView mMapView;
	private MapController mMapController = null;
	private GeoPoint geoPoint;
	private MKSearch mkSearch;

	private boolean firstLocation = true;
	private final int LOCATION_SUCCESS = 0x1120;
	private final int LOCATION_FAIL = LOCATION_SUCCESS + 1;

	private GsooApplication app;
	private LocationClient mLocationClient;
	public MyLocationListenner myListener = new MyLocationListenner();

	private RelativeLayout left_rl;
	private RelativeLayout right_rl;
	private TextView position_tv;
	private ImageButton backIB;
	private TextView location_tv;
	private TextView center_tv;
	private SharePreferenceUtil util;
	private EditText search_et;
	private String cityName;

	private Dialog resultDialog;
	private List<PoiEnity> poiList;
	private TextView reg_tv;
	private RelativeLayout left;
	private ImageButton left_ib;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;

		setContentView(R.layout.activity_address_map);
		util = new SharePreferenceUtil(this, "setting");
		initRes();
		app = (GsooApplication) getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(this);
			/**
			 * 如果BMapManager没有初始化则初始化BMapManager
			 */
			app.mBMapManager.init(GsooApplication.strKey,
					new GsooApplication.MyGeneralListener());
		}
		mkSearch = new MKSearch();
		mkSearch.init(app.mBMapManager, mkSearchListener);
		// poiList = new ArrayList<PoiEnity>();
		// poiAdapter = new PoiResultAdapter(this, poiList);
		// resultDialog = createSearchDialog();

	}

	private int searchMode = 0;// 0确定 1 搜索

	private void initRes() {

		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				finish();
			}
		});
		//left_ib.setBackgroundResource(R.drawable.translate);
		left = (RelativeLayout) findViewById(R.id.left);
		marker_iv = (ImageView) findViewById(R.id.maker);
		address_tv = (TextView) findViewById(R.id.address);
		mMapView = (MapView) findViewById(R.id.bmapView);
		address_tv.setText("正在定位中...");
		address_tv.setVisibility(View.GONE);
		location_tv = (TextView) findViewById(R.id.reg_tv);
		location_tv.setText("确定");
		location_tv.setOnClickListener(this);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("地址选择");
		search_et = (EditText) findViewById(R.id.search_et);
		search_et.addTextChangedListener(searchTextWatcher);

	}

	TextWatcher searchTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			if (s.length() == 0) {
				location_tv.setText("确定");
				searchMode = 0;
			} else {
				location_tv.setText("搜索");
				searchMode = 1;
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case LOCATION_SUCCESS:
				MapInfo info = (MapInfo) msg.obj;
				if (info != null) {
					geoPoint = new GeoPoint((int) (info.getLat() * 1e6),
							(int) (info.getLng() * 1e6));
					if (info.getAddress() == null) {
						mkSearch.reverseGeocode(geoPoint);
						address_tv.setText("地址获取中..");
					} else {
						address_tv.setText(info.getAddress());
						address_tv.setVisibility(View.VISIBLE);
					}

					Log.e("wxf", "mapEnity.getLat()" + info.getLat()
							+ ",mapEnity.getLng()" + info.getLng());
					mMapView.getController().setCenter(geoPoint);
					mMapController.animateTo(geoPoint);
				} else {

				}
				break;
			case LOCATION_FAIL:
				address_tv.setText("定位失败");
				break;
			}
		};
	};

	private void initMap() {
		/**
		 * 获取地图控制器
		 */
		mMapController = mMapView.getController();
		/**
		 * 设置地图是否响应点击事件 .
		 */
		mMapController.enableClick(true);
		/**
		 * 设置地图缩放级别
		 */
		mMapController.setZoom(18);
		/**
		 * 显示内置缩放控件
		 */
		mMapView.setBuiltInZoomControls(true);
		mMapView.regMapViewListener(app.mBMapManager, mapViewListener);

		mMapView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					address_tv.setVisibility(View.GONE);
					break;
				case MotionEvent.ACTION_UP:
					address_tv.setText("加载中..");
					address_tv.setVisibility(View.VISIBLE);
					location_tv.setVisibility(View.GONE);
					break;
				}
				return false;
			}
		});
	}

	private boolean isAddress = false;
	private String address = null;

	@Override
	protected void onResume() {
		address = getIntent().getStringExtra("address");
		cityName = util.loadStringSharedPreference("cityName");
		initMap();
		if (address != null) {
			isAddress = true;
			firstLocation = false;
			mkSearch.geocode(address, cityName);
		} else {
			isAddress = false;
			firstLocation = true;
			initLocation();
		}

		super.onResume();
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (mLocationClient != null) {
			mLocationClient.stop();
		}
		firstLocation = false;
		mMapView.destroy();
		super.onDestroy();
	}

	public void initLocation() {
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		// option.setAddrType("all");
		option.setOpenGps(true);
		// option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先;
		// option.setPoiNumber(10);
		option.setScanSpan(5000);
		// option.disableCache(true);
		option.setCoorType("bd09ll");
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	/**
	 * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());

			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				// sb.append("\nspeed : ");
				// sb.append(location.getSpeed());
				// sb.append("\nsatellite : ");
				// sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\n省：");
				sb.append(location.getProvince());
				sb.append("\n市：");
				sb.append(location.getCity());
				sb.append("\n区/县：");
				sb.append(location.getDistrict());
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			Log.i("wxf", "address:" + sb.toString());
			if (firstLocation) {
				MapInfo mapEnity = new MapInfo(location.getLatitude(),
						location.getLongitude(), location.getAddrStr());
				Message msg = handler.obtainMessage();
				msg.what = LOCATION_SUCCESS;
				msg.obj = mapEnity;
				handler.sendMessage(msg);
				firstLocation = false;
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				Message msg = handler.obtainMessage();
				msg.what = LOCATION_FAIL;
				handler.sendMessage(msg);
				return;
			}
			StringBuffer sb = new StringBuffer(256);
			sb.append("Poi time : ");
			sb.append(poiLocation.getTime());
			sb.append("\nerror code : ");
			sb.append(poiLocation.getLocType());
			sb.append("\nlatitude : ");
			sb.append(poiLocation.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(poiLocation.getLongitude());
			sb.append("\nradius : ");
			sb.append(poiLocation.getRadius());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(poiLocation.getAddrStr());
			}
		}
	}

	MKMapViewListener mapViewListener = new MKMapViewListener() {

		@Override
		public void onClickMapPoi(MapPoi arg0) {

		}

		@Override
		public void onGetCurrentMap(Bitmap arg0) {

		}

		@Override
		public void onMapAnimationFinish() {
			mMapView.getController().setZoom(mMapView.getZoomLevel());
			mkSearch.reverseGeocode(mMapView.getMapCenter());

		}

		@Override
		public void onMapMoveFinish() {

			GeoPoint ptCenter = new GeoPoint(mMapView.getMapCenter()
					.getLatitudeE6(), mMapView.getMapCenter().getLongitudeE6());
			mkSearch.reverseGeocode(ptCenter);
		}

	};

	MKSearchListener mkSearchListener = new MKSearchListener() {

		@Override
		public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {

		}

		@Override
		public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {

		}

		@Override
		public void onGetSuggestionResult(MKSuggestionResult res, int iError) {
			// if (iError != 0 || res == null) {
			// Toast.makeText(AddressActivity.this, "抱歉，未找到结果",
			// Toast.LENGTH_LONG).show();
			// return;
			// }
			// int nSize = res.getSuggestionNum();
			// String[] mStrSuggestions = new String[nSize];
			// for (int i = 0; i < nSize; i++) {
			// mStrSuggestions[i] = res.getSuggestion(i).city
			// + res.getSuggestion(i).key;
			// LogUtil.d("wxf", "poi:" + mStrSuggestions[i]);
			// }
		}

		@Override
		public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {

		}

		@Override
		public void onGetPoiDetailSearchResult(int arg0, int arg1) {

		}

		@Override
		public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {

		}

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {

		}

		@Override
		public void onGetAddrResult(MKAddrInfo res, int arg1) {

			if (res == null) {
				Toast.makeText(AddressActivity.this, "位置获取失败", 500).show();
				return;
			}

			if (res.type == MKAddrInfo.MK_GEOCODE) {
				mMapView.getController().animateTo(res.geoPt);
				mMapController.setCenter(res.geoPt);
				address_tv.setText(address);

				return;
			}
			address_tv.setText(res.strAddr);
			location_tv.setVisibility(View.VISIBLE);
		}
	};

	private MyOverlay mOverlay;

	public class MyOverlay extends ItemizedOverlay {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}
	}

	private Intent intent;
	private String latStr;
	private String lngStr;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.reg_tv:
			latStr = String
					.valueOf(mMapView.getMapCenter().getLatitudeE6() / 1E6);
			lngStr = String
					.valueOf(mMapView.getMapCenter().getLongitudeE6() / 1E6);
			intent = new Intent();
			intent.putExtra("address", address_tv.getText().toString());
			intent.putExtra("lat", latStr);
			intent.putExtra("lng", lngStr);
			LogUtil.d("wxf", "address:" + address_tv.getText().toString());
			setResult(RESULT_OK, intent);
			finish();

			break;
		}
	}

	/**
	 * 暂且没用
	 */
	private ListView search_view;
	private PoiResultAdapter poiAdapter;

	private Dialog createSearchDialog() {
		LayoutInflater inflater = getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.search_result_dialog_view, null);
		TextView hint_text = (TextView) dialog_rl
				.findViewById(R.id.confirm_dialog_hint_text);
		hint_text.setText("搜索结果");
		final Dialog dialog = new Dialog(this, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		search_view = (ListView) dialog_rl.findViewById(R.id.result_listView);
		search_view.setAdapter(poiAdapter);
		return dialog;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
